<?php

App::uses('AppController', 'Controller');

/**
 * Customers Controller
 *
 */
class CustomersController extends AppController {

    /**
     * Scaffold
     *
     * @var mixed
     */
    public $scaffold;
    public $uses = array('Customer', 'CustomerData', 'Property','PropertyType');

    public function listAll() {
        $this->set('all', $this->Customer->listAll());
    }
    
    public function view($id=NULL){
        if($id != NULL){          
            $data = $this->Customer->getAllDetails($id);
            $this->set('data',$data);
            $this->set('pros',$this->PropertyType->findById($data['CustomerData'][0]['property_type_id']));
        }else{
            $this->redirect('/Customers/listAll');
        }        
    }

    public function register() {
        if ($this->request->is('post')) {
            //debug($this->request->data);
            $this->request->data['CustomerData']['demand'] = 'Sell';
            $this->Customer->set($this->request->data['Customer']);
            if (!isset($this->request->data['CustomerData']['preference'])) {
                $this->request->data['CustomerData']['preference'] = '';
            }
            $this->CustomerData->set($this->request->data['CustomerData']);
            $resCus = $this->Customer->validates();
            $resCusData = $this->CustomerData->validates();
            if ($resCus && $resCusData) {
                if ($this->Customer->save()) {
                    $prefers = '';
                    $rePres = $this->request->data['CustomerData']['preference'];
                    for ($i = 0; $i < sizeof($rePres); $i++) {
                        $prefers = $prefers . ' ' . $rePres[$i];
                    }
                    $customerId = $this->Customer->getLastInsertID();
                    $this->CustomerData->set(array(
                        'customer_id' => $customerId,
                        'preference' => $prefers
                    ));
                    $this->CustomerData->save();
                    $this->Session->setFlash('Saved');
                    $this->redirect('/');
                }
            }
        }

        $preferences = array('Fully-furnished', 'Fitness', 'Swimming Pool', 'Mountain View', 'River View', 'Pets Allows');
        $bedRooms = array('Studio', '1 Bedroom', '2 Bedroom', '3 Bedroom', '4 Bedroom or more');
        $locations = array('Chiang mai', 'Bangkok', 'Others');

        $this->set('locations', $locations);
        $this->set('bedRooms', $bedRooms);
        $this->set('preferences', $preferences);
        $this->set('properties', $this->Property->listAll());
    }

    public function delete($id = NULL) {
        if ($id != NULL) {
            if ($this->Customer->delete($id)) {
                $this->Session->setFlash('Remove Success!!');
            }
        }
        $this->redirect('/Customers/listAll');
    }

}
